package com.wangge.test1.lambda;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

import com.wangge.test1.Person;

/**lambda表达式与函数式接口的混合使用
 * @author yangqc
 *
 */
public class Lambda {
	@Test
	public void test1() {
		Formula f1 = new Formula() {

			@Override
			public Object calcuate(int b) {
				return sqrt(b);
			}
		};
		System.out.println(f1.calcuate(25));
	}

	@Test
	public void testSort() {
		List<String> namesList = Arrays.asList("Bsdf", "Wsfs", "Asfs", "Tsdf");
		System.out.println(namesList);
		Collections.sort(namesList, (a, b) -> a.compareTo(b));
		System.out.println(namesList);
	}

	@Test
	public void testFunc() {
		Converter<Integer, String> convert = (f) -> Integer.valueOf(f);
		String str = "1234";
		System.out.println(convert.handle(str));
	}

	/**
	 * ::方法表达式,引用某个类的方法作为某接口的实现
	 */
	@Test
	public void testMethodReference() {
		class Something {
			String startwith(String str) {
				return String.valueOf(str.charAt(0));
			}
		}
		Something something = new Something();
		Converter<String, String> convert = something::startwith;
		System.out.println(convert.handle("sadfs"));
	}
	
	
	

	@Test
	public void testConstructorReference() {
		
		PersonFactory<Person> personFatory = Person::new;
		Person p1 = personFatory.create("我是大英雄", "dB吉林省的");
		System.out.println(p1.firstName);
	}

	interface PersonFactory<P> {
		P create(String firename, String lastName);
	}

	/**
	 * lambda访问局部变量时只能访问final类型或者实际上值未变化的变量; 且不能对局部变量进行读写;
	 *  但对实例域和静态变量有读写权限
	 *  然lambda不能访问默认的接口方法;
	 */
	@SuppressWarnings("unused")
	private int num = 15;

	@Test
	public void testLocalconstant() {
		int i = 2;
		Converter<String, Integer> convert = (f) -> String.valueOf(f + i);
		System.out.println(convert.handle(8));
		convert = (f) -> {
			num = 20;
			return String.valueOf(20 + f);
		};
		System.out.println(convert.handle(14));
		//Formula f=(b)->sqrt(b);    然lambda不能访问默认的接口方法; 
	}

	public Lambda() {
		super();
	}

}
